package com.blog.util;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public final class JSONUtils {
	
	/**
	 * 从JSON字符串中取得对象
	 * Example:
	 * jsonStr:{attrName1:{userName:'name1', age:33},attrName2:{roleName:'admin', roleId:2}}
	 * User user = getBeanWithJsonStr(jsonStr, 'attrName', User.class)
	 * 
	 * @param jsonStr 
	 * @param attrName
	 * @param clazz
	 * @return
	 */
	public static <T> T getBeanWithJsonStr(String jsonStr, String attrName, Class<T> clazz) {
    	if (StringUtils.isBlank(jsonStr)) {
    		return null;
    	}
    	
    	if (StringUtils.isBlank(attrName)) {
    		return JSON.parseObject(jsonStr, clazz);
    	}
    	
    	JSONObject jsonObj = JSON.parseObject(jsonStr);
    	Object attrJsonObj = jsonObj.get(attrName);
    	T resultObj = JSON.parseObject(JSON.toJSONString(attrJsonObj), clazz);
    	
    	return (T) resultObj;
    }
	
	public static <T> List<T> getArrayWithJsonStr(String jsonStr, String attrName , Class<T> clazz){
		if (StringUtils.isBlank(jsonStr)) {
    		return null;
    	}
    	
    	if (StringUtils.isBlank(attrName)) {
    		return null;
    	}
    	JSONObject jsonObj = JSON.parseObject(jsonStr);
    	List<T> array = JSON.parseArray(jsonObj.getString(attrName),clazz);

		return array;
	}
	
	
	public static <T> List<T> getArrayWithJsonArray(String jsonStr, Class<T> clazz){
		if (StringUtils.isBlank(jsonStr)) {
    		return null;
    	}
    	List<T> array = JSON.parseArray(jsonStr,clazz);

		return array;
	}
	
	public static String getString(String jsonStr, String attrName) {
		if (StringUtils.isBlank(jsonStr)) {
    		return "";
    	}
    	
    	if (StringUtils.isBlank(attrName)) {
    		return "";
    	}
    	JSONObject jsonObj = JSON.parseObject(jsonStr);
    	return jsonObj.getString(attrName);
	}
	
	public static boolean getBoolean(String jsonStr, String attrName) {
		if (StringUtils.isBlank(jsonStr)) {
    		return false;
    	}
    	
    	if (StringUtils.isBlank(attrName)) {
    		return false;
    	}
    	JSONObject jsonObj = JSON.parseObject(jsonStr);
    	return jsonObj.getBooleanValue(attrName);
	}
	
	public static Long getLong(String jsonStr, String attrName) {
		if (StringUtils.isBlank(jsonStr)) {
    		return 0L;
    	}
    	
    	if (StringUtils.isBlank(attrName)) {
    		return 0L;
    	}
    	JSONObject jsonObj = JSON.parseObject(jsonStr);
    	return jsonObj.getLong(attrName);
	}
}
